<template>
  <div class="cmt-container">
    <h3 class="submit-comment">发表评论</h3>
    <hr>
    <textarea class="cmt-area" placeholder="请输入评论内容(最多评论120)" v-model="msg"></textarea>
    <mt-button type="primary" size="large" @click="addcomment">发表评论</mt-button>
    <div class="cmt-list">
      <div class="cmt-item" v-for="(item,i) in comments" :key="i">
        <div class="cmt-title">
          第{{i+1}}楼&nbsp;&nbsp;用户:{{item.user_name}}&nbsp;&nbsp;发表时间:{{item.add_time | dateformat}}
        </div>
        <div class="cmt-body" >{{item.content === 'undefined' ? '此用户很懒,没有发表任何评论':item.content}}</div>
      </div>
    </div>
    <mt-button type="danger" size="large" plain @click="morecomments" class="more">加载更多</mt-button>
  </div>
</template>
<script>
import {Toast} from 'mint-ui';
export default {
  data() {
    return {
      pageIndex:1,
      comments:[],
      msg:""
    }
  },
  created(){
    this.getAllComments()
  },
  methods: {
    getAllComments(){
      this.$http.get('api/getcomments/'+ this.id +'?pageindex='+this.pageIndex)
      .then(result=>{
        if(result.body.status === 0) {
          // console.log(result.body)
          this.comments = this.comments.concat(result.body.message)
        }
      })
    },
    morecomments(pageIndex){
      this.pageIndex++;
      this.getAllComments()
    },
    addcomment(){
      // 校验评论信息是否为空
      if(this.msg.trim().length === 0) {
        return Toast('评论信息不能为空!')
      }
      this.$http.post('api/postcomment/'+this.id,{content:this.msg.trim()}).then(result=>{
        if(result.body.status === 0) {
          console.log(result.body)
          var cmt = {
            user_name: "匿名用户",
            add_time:Date.now(),
            content:this.msg.trim()
          }
          this.comments.unshift(cmt);
          this.msg = "";
        }
      })
    }
  },
  props:['id']
}
</script>
<style lang="scss" scoped>
  .cmt-container {
    .submit-comment {
      font-size:18px;
    }
    .cmt-area {
      height: 85px;
      font-size: 12px;
    }
    .cmt-list {
      .cmt-title {
        background-color: #ccc;
        line-height: 30px;
        font-size: 12px;
        margin-top: 8px;
      }
      .cmt-body {
        line-height: 35px;
        font-size: 14px;
        text-indent: 2em;
      }
    }
    .more {
      margin-bottom: 10px;
    }
  }
</style>